package com.bestcem.xm.script.grpc.client.impl;

import com.bestcem.bp.xm.user.grpc.v1.enums.OrgStatusEnum;
import com.bestcem.bp.xm.user.grpc.v1.services.*;
import com.bestcem.xm.common.core.constant.GrpcClientNames;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.label.constant.Constants;
import com.bestcem.xm.script.grpc.client.ScriptUserClient;
import io.grpc.StatusRuntimeException;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ming.xue <ming.xue@idiaoyan.com>
 * @desc 用户客户端
 * @date 2021-11-11
 */
@Slf4j
@Component("scriptUserClient")
public class ScriptUserClientImpl implements ScriptUserClient {

    @GrpcClient(GrpcClientNames.DS_USER)
    OrgServiceGrpc.OrgServiceBlockingStub orgServiceBlockingStub;

    @GrpcClient(GrpcClientNames.DS_USER)
    private UserServiceGrpc.UserServiceBlockingStub userServiceBlockingStub;


    /**
     * 获取企业标识
     *
     * @param orgCode
     * @return
     */
    public ServiceResult<String> getOrgId(String orgCode) {
        List<OrgStatusEnum.OrgStatus> list = Collections.singletonList(OrgStatusEnum
                .OrgStatus.ACTIVATED);
        ListOrgsRequest request = ListOrgsRequest.newBuilder().addAllStatuses(list).build();
        ListOrgsResponse response;
        try {
            response = orgServiceBlockingStub.listOrgs(request);
        } catch (StatusRuntimeException e) {
            log.error("【联系人】获取企业列表失败，request:{}", request, e);
            return ServiceResult.fail("【联系人】获取企业列表失败");
        }
        if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
            log.error("【联系人】获取企业列表失败, request: {}, response: {}", request, response);
            return ServiceResult.fail("【联系人】获取企业列表失败");
        }
        List<Organization> organizations = response.getOrgsList();
        organizations = organizations.stream()
                .filter(organization -> StringUtils.equals(orgCode, organization.getCode()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(organizations) || organizations.size() > 1) {
            return ServiceResult.fail("企业代码无效");
        }

        return ServiceResult.success(organizations.get(0).getId());
    }

    /**
     * 获取管理用户标识
     *
     * @return
     */
    @Override
    public ServiceResult<String> getAdminUserId() {
        ListUsersRequest request = ListUsersRequest.newBuilder().build();
        ListUsersResponse response;
        try {
            response = userServiceBlockingStub.listUsers(request);
        } catch (StatusRuntimeException e) {
            log.error("【联系人】根据条件获取用户失败，request:{}", request, e);
            return ServiceResult.fail("【联系人】根据条件获取用户失败");
        }
        if (response.getStatus().getCodeValue() != Constants.SUCCESS) {
            log.error("【联系人】根据条件获取用户失败，response:{}", response);
            return ServiceResult.fail("【联系人】根据条件获取用户失败");
        }
        List<User> users = response.getUsersList();
        if (CollectionUtils.isEmpty(users)) {
            return ServiceResult.fail("管理用户不存在");
        } else if (users.size() > 1) {
            return ServiceResult.fail("用户多于1个，无法确定管理员");
        }
        return ServiceResult.success(users.get(0).getId());
    }
}
